package com.cxdr.awsips.distribute.file;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;

import com.cxdr.awsips.common.logger.LogFactory;
import com.cxdr.awsips.distribute.bean.ReportFileLog;
import com.cxdr.awsips.distribute.bean.Target;
import com.cxdr.awsips.distribute.config.SystemConfig;
import com.cxdr.awsips.distribute.rule.FileNameRule;
import com.cxdr.awsips.distribute.rule.TimeRule;

public class LocalFileHelper implements FileHelper {
	private static Logger logger = LogFactory
			.makeNewLogger(LocalFileHelper.class);
	private String remoteDir;
	private String HOME_WORK;
	private String localDir;
	private Target target;
	private FileNameRule fileNameRule;
	private TimeRule timeRule;
	private List<FileNameRule> fileNameRules = new ArrayList<FileNameRule>();
//	private List<StationRule> stationRules = new ArrayList<StationRule>();
	private List<TimeRule> timeRules = new ArrayList<TimeRule>();
	private long keyTime;
	private boolean sub;
	public LocalFileHelper(){
		if (StringUtils.isBlank(remoteDir)) {
			this.remoteDir = SystemConfig.get("path.source");
			HOME_WORK = this.remoteDir;
		}
	}
	public LocalFileHelper(Target target) {
		this.target = target;
		this.remoteDir = target.getFolder();
		if (StringUtils.isBlank(remoteDir)) {
			this.remoteDir = SystemConfig.get("path.source");
			HOME_WORK = this.remoteDir;
		}
		this.localDir = SystemConfig.get("path.source");
		if (target != null && !StringUtils.isBlank(target.getBackpath())) {
			File backDir = new File(target.getBackpath());
			if (!backDir.isDirectory()) {
				backDir.mkdirs();
			}
		}
	}

	@Override
	public Set<File> scanDir() {
		return scanDir(getRemoteDir());
	}

	@Override
	public Set<File> scanDir(String dir) {
		return scanDir(dir, "txt");
	}

	@Override
	public Set<File> scanDir(String dir, String fileType) {
		String path = dir;
		logger.info("开始扫描目录" + path + "....");
		Set<File> set = new HashSet<File>();
		File fileDir = new File(path);
		if (!fileDir.isDirectory()) {
			logger.info("目录" + path + "不存在，请检查源目录");
			// FileScaner.this.cancel();
			return set;
		}
		_scanDir(set,new File(dir),fileType);
		return set;
	}
	private void _scanDir(Set<File> set,File fileDir, String fileType){
		String path = fileDir.getAbsolutePath();
		String localPath = localDir;
		setRemoteDir(path);
		if(isSub()){
			setLocalDir(localPath+File.separator+fileDir.getName());
		}
		logger.info("开始扫描目录" + path + "....");
		if (!fileDir.isDirectory()) {
			logger.info("目录" + path + "不存在，请检查源目录");
			return ;
		}
		File[] files = fileDir.listFiles();
		logger.info("扫描到 " + files.length + "个文件");
		Date currentTime = new Date();
		if (files != null) {
			for (File file : files) {
				if(file.isDirectory()){
					_scanDir(set,file,fileType);
					continue;
				}
				/*************************过滤文件*****************************/
				boolean isAccept = false;
				String fileName = file.getName();
				for(FileNameRule fileNameRule:fileNameRules){
					if (fileNameRule != null && !fileNameRule.accept(fileName)) {
						isAccept = true;
						break;
					}
				}
				if(isAccept) continue;
				Date fileTime = new Date(file.lastModified());
				for (TimeRule timeRule : timeRules) {
					if (timeRule != null
							&& !timeRule.accept(fileTime)) {
						isAccept = true;
						break;
					}
				}
				if(isAccept) continue;
				/*************************删除过期文件*****************************/
				if(keyTime > 0){
					ReportFileLog fileLog = new ReportFileLog();
					fileLog.setFile_name(fileName, true);
					if(fileLog.getObser_time().getTime()+keyTime < currentTime.getTime()){
						deleteFile(fileName);
					}
				}
				if (StringUtils.isBlank(fileType)) {
					File localfile = getFile(file.getName());
					if (localfile != null) {
						logger.debug("添加文件:" + localfile.getAbsolutePath());
						set.add(localfile);
					}
					continue;
				}
				if (StringUtils.endsWithIgnoreCase(file.getName(), "."
						+ fileType)) {
					File localfile = getFile(file.getName());
					if (localfile != null) {
						logger.debug("添加文件:" + localfile.getAbsolutePath());
						set.add(localfile);
					}
				}
			}
		}
		setRemoteDir(fileDir.getParent());
		if(isSub()){
			setLocalDir(localPath);
		}
	}
	public File getFile(String fileName) {
		File localFile = null;
		if (localDir.equals(remoteDir)) {
			logger.info("local is remote!");
			return new File(remoteDir + File.separator + fileName);
		}
		try {
			localFile = new File(localDir + File.separator + fileName);
//			localFile = new File(localDir + File.separator + fileName);
			if (localFile.isFile()) {
				localFile.delete();
			}
			File remoteFile = new File(remoteDir + File.separator + fileName);
			logger.info("下载文件："+remoteFile.getAbsolutePath());
			FileUtils.copyFile(remoteFile, localFile);
			if (target != null) {
				if (!StringUtils.isBlank(target.getBackpath())) {
					File backcFile = new File(target.getBackpath()
							+ File.separator + fileName);
					if (backcFile.isFile()) {
						backcFile.delete();
					}
					logger.info("备份远程文件：" + remoteFile.getAbsolutePath());
					if (!remoteFile.renameTo(backcFile)) {
						remoteFile.delete();
					}
				} else {
					logger.info("删除远程文件：" + remoteFile.getAbsolutePath());
					remoteFile.delete();
				}
			}
		} catch (Exception e) {
			logger.error("复制文件错误", e);
			return null;
		}
		return localFile;
	}

	@Override
	public void open() throws IOException {

	}

	public void getDir(String dir) {
		try {
			FileUtils.copyFile(new File(remoteDir), new File(localDir));
		} catch (Exception e) {
		}
	}

	@Override
	public void close() {

	}

	@Override
	public boolean renameFile(String from, String to) {
		boolean result = false;
		File fromF = new File(remoteDir + File.separator + from);
		try {
			result = fromF.renameTo(new File(remoteDir + File.separator + to));
		} catch (Exception e) {
			logger.error("重命名文件错误", e);
		}
		return result;
	}

	@Override
	public boolean deleteFile(String fileName) {
		boolean result = false;
		try {
			result = new File(remoteDir + File.separator + fileName).delete();
		} catch (Exception e) {
		}
		return result;
	}

	@Override
	public boolean uploadFile(File file) {
		String filePath = file.getAbsolutePath();
		logger.info("开始上传文件：" + filePath);
		String separator = File.separator;
		if (separator.equals("\\")){
			separator = "\\\\";
		}
		String[] fileRelatePath = filePath.replace(localDir, "").split(separator);
		StringBuilder rDir = new StringBuilder(remoteDir);
		for (String path : fileRelatePath) {
			if(path.endsWith(".java")||StringUtils.isBlank(path)||path.endsWith(".txt")){
				continue;
			}
			rDir.append(File.separator).append(path);
		}
		File rDird = new File(rDir.toString());
		if(!rDird.isDirectory()){
			if (!rDird.mkdirs()){
				logger.error("create diretory :"+rDir.toString()+" error,could not update file");
			}
		}
		try {
			File rFile = new File(rDir.append(File.separator).append(file.getName()).toString());
			FileUtils.copyFile(file,rFile);
			logger.info("上传文件:" + rFile.getAbsolutePath() + "成功");
		} catch (Exception e) {
			logger.error("复制文件错误", e);
			logger.error("localfile:" + localDir + File.separator +  file.getName());
			logger.error("remotefile:" + remoteDir + File.separator +  file.getName());
			return false;
		}
		return true;
	}

	@Override
	public void setRemoteDir(String remoteDir) {
		this.remoteDir = remoteDir;
		
	}

	@Override
	public void setLocalDir(String localDir) {
		this.localDir = localDir;
		File localDirD = new File(localDir);
		if (!localDirD.isDirectory()) {
			localDirD.mkdirs();
		}
	}

	public String getRemoteDir() {
		return remoteDir;
	}


	public List<FileNameRule> getFileNameRules() {
		return fileNameRules;
	}

	public void setFileNameRules(List<FileNameRule> fileNameRules) {
		this.fileNameRules = fileNameRules;
	}

	public List<TimeRule> getTimeRules() {
		return timeRules;
	}

	public void setTimeRules(List<TimeRule> timeRules) {
		this.timeRules = timeRules;
	}
	public long getKeyTime() {
		return keyTime;
	}

	public void setKeyTime(long keyTime) {
		this.keyTime = keyTime;
	}

	public boolean isSub() {
		return sub;
	}

	public void setSub(boolean sub) {
		this.sub = sub;
	}
	public static void main(String[] args) {
		LocalFileHelper local = new LocalFileHelper();
//		local.setRemoteDir("E:\\Mydocument\\GX\\广西自动气象站——分发1.0\\2-13");
//		local.setLocalDir("2-13-local");
//		local.scanDir();
		local.setLocalDir("E:\\Mydocument\\GX\\广西自动气象站——分发1.0");
		local.setRemoteDir("m");
		File file = new File("E:\\Mydocument\\GX\\广西自动气象站——分发1.0\\2-13\\Z_SURF_C_BENN-REG_20120116214825_O_AWS_FTM.txt");
		local.uploadFile(file);
		File f2 = new File("E:\\Mydocument\\GX\\广西自动气象站——分发1.0\\2-13\\ss\\Z_RADI_C_BENN_20120116214826_O_ARS_FTM.txt");
		local.uploadFile(f2);
	}
}
